package com.government.member.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.government.common.core.domain.entity.SysUser;
import com.government.member.domain.BrowsingHistory;
import com.government.member.domain.UserHobby;
import com.government.member.mapper.BrowsingHistoryMapper;
import com.government.member.service.BrowsingHistoryService;
import com.government.system.domain.vo.WebAuthVo;
import com.government.system.service.WebRoleAuthService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class BrowsingHistoryServiceImpl implements BrowsingHistoryService {
    @Autowired
    private BrowsingHistoryMapper browsingHistoryMapper;
    @Autowired
    private WebRoleAuthService webRoleAuthService;

    @Override
    public List<BrowsingHistory> getBrowsingHistoryByUserId(Long userId) {

        String createTime = "";
        if(!SysUser.isAdmin(userId)) {
            WebAuthVo webAuthVo = webRoleAuthService.getAuthContent();
            int bc = Integer.parseInt(webAuthVo.getBc());
            if (bc == 0) {
                return Lists.newArrayList();
            }
            createTime = DateUtil.formatDate(DateUtil.offsetDay(new Date(), -bc));
        }
        return browsingHistoryMapper.getBrowsingHistory(userId, createTime);
    }

    @Override
    public int insertBrowsingHistory(BrowsingHistory browsingHistory) {

        BrowsingHistory browsingHistoryTemp = browsingHistoryMapper.selectOne(Wrappers.<BrowsingHistory>lambdaQuery().eq(BrowsingHistory::getSourceId, browsingHistory.getSourceId())
                .eq(BrowsingHistory::getSourceType, browsingHistory.getSourceType())
                .eq(BrowsingHistory::getUserId, browsingHistory.getUserId()));
        if (Objects.nonNull(browsingHistoryTemp)) {
            browsingHistoryTemp.setCreateTime(new Date());
            return browsingHistoryMapper.updateById(browsingHistoryTemp);
        } else {
            return browsingHistoryMapper.insert(browsingHistory);
        }


    }

    @Override
    public int clearBrowsingHistory(Long userId) {

        return browsingHistoryMapper.delete(Wrappers.<BrowsingHistory>lambdaQuery().eq(BrowsingHistory::getUserId, userId));
    }

    /**
     * 用户浏览数量
     *
     * @return
     */
    @Override
    public int selectBrowsingCountByUserId(Long userId) {
        return browsingHistoryMapper.selectCount(Wrappers.<BrowsingHistory>lambdaQuery().eq(BrowsingHistory::getUserId, userId)
        );
    }
}
